package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.impl.DepartmentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

//类似之前的Servlet
//请求用户的请求和相应

@Controller//IOC注解，将Controller交给Spring容器管理
@RequestMapping("/department")
public class DepartmentController {

    //自动去Spring容器中找到对应类型或者名称的对象并设置给当前字段
    @Autowired
    private IDepartmentService service = new DepartmentServiceImpl();

    //处理查询的请求
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){

        //登录的检查



        //查询到所有的部门
        PageResult result = service.query(qo);
        //将查询到的部门共享给页面
        model.addAttribute("result",result);

        //指定页面跳转的视图
        return "department/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id){
        //从数据库中将对应id的部门删除
        service.delete(id);
        //重新访问list方法执行查询并跳转到list.jsp页面
        //默认的跳转方式是请求转发
        //使用redirect:前缀修改跳转的方式为重定向
        return "redirect:/department/list.do";
    }

    @RequestMapping("/input")
    public String input(Long id, Model model){
        if(id !=null){
            Department dept = service.get(id);
            model.addAttribute("entity", dept);
        }
        //跳转到input.jsp页面
        return "department/input";
    }

    //执行保存或更新
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Department dept){
        if(dept.getId() !=null){
            //更新
            service.update(dept);
        }else{
            //保存
            service.save(dept);
        }

        return "redirect:/department/list.do";
    }
}
